package com.steve.combat.algorithm.search;

/**
 * @Author: STEVE
 * @Description: 查找指定字符串第一次或最后一次出现的位置
 * @since: 2025-05-30
 */
public class GetMatchingIndex {

    public static void main(String[] args) {
        String str = "ssssdeffsdfsdf";
        getFirstMatchingIndex(str, "sdf");
        getLastMatchingIndex(str, "sdf");
    }

    /**
     * 查找指定字符第一次出现的位置
     */
    public static void getFirstMatchingIndex(String input, String query) {
        char[] inputChars = input.toCharArray();
        char[] queryChars = query.toCharArray();
        int inputLength = input.length();
        int queryLength = query.length();

        int inputIndex = 0;
        int queryIndex = 0;

        while (inputIndex < inputLength && queryIndex < queryLength) {
            if (inputChars[inputIndex] == queryChars[queryIndex]) {
                queryIndex++;
                inputIndex++;
            } else {
                inputIndex = inputIndex - queryIndex + 1;
                queryIndex = 0;
            }
        }
        int index = queryIndex == queryLength ? (queryLength > 1 ? inputIndex - queryLength : inputIndex - 1) : -1;
        System.out.println("first matching index: " + index);
    }

    /**
     * 查找指定字符最后一次出现的位置
     */
    public static void getLastMatchingIndex(String input, String query) {
        char[] inputChars = input.toCharArray();
        char[] queryChars = query.toCharArray();
        int inputLength = input.length();
        int queryLength = query.length();

        int inputIndex = inputLength - 1;
        int queryIndex = queryLength - 1;
        int matchingLength = 0;
        while (inputIndex >= 0 && queryIndex >= 0) {
            if (inputChars[inputIndex] == queryChars[queryIndex]) {
                inputIndex--;
                queryIndex--;
                matchingLength++;
            } else {
                inputIndex = matchingLength <= 0 ? inputIndex - 1 : inputIndex;
                queryIndex = queryLength - 1;
                matchingLength = 0;
            }
        }
        System.out.println("last matching index: " + ((matchingLength == queryLength) ? inputIndex + 1 : -1));
    }

}
